package com.cloud.lcnorder.controller;

import com.alibaba.fastjson.JSONObject;
import com.cloud.lcnorder.dao.TxOrderMapper;
import com.cloud.lcnorder.entity.TxOrder;
import com.codingapi.txlcn.tc.annotation.LcnTransaction;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.client.RestTemplate;

@RestController
@SuppressWarnings("all")
public class MainController {

    @Autowired
    TxOrderMapper mapper;

    @Autowired
    RestTemplate restTemplate;


    @PostMapping("/createOrder")
    @Transactional
    //开启 lcn分布式事务
    @LcnTransaction
    public String createOrder(){
        // 创建订单
        TxOrder order = TxOrder.Build().id(1).orderName("商品").build();
        //存数据库
        mapper.insertTxOrder(order);

        JSONObject data = new JSONObject();
        data.put("payName",order.getOrderName());

        //调用支付系统
        restTemplate.postForEntity("http://lcn-pay/payOrder",data, String.class);
        //手动抛出异常，让分布式事务回滚
         int i = 1/0;
        return "操作成功";
    }

}
